﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PdfTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string filePath = @"E:\V-Label\新版VLable20210416\20210420\80x120_b8.pdf";
            // 原比例
            //CreatePdf();
        }

        /// <summary>
        /// 创建指定尺寸的黑色背景的PDF
        /// </summary>
        /// <param name="outFilePath"></param>
        /// <param name="width"></param>
        /// <param name="hight"></param>
        /// <returns></returns>
        bool CreatePdf(string outFilePath, float width, float hight)
        {
            Document doc = null;
            try
            {
                // PDF页面尺寸
                iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(width, hight);
                // PDF设置背景色    
                rec.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.Black);
                // 创建Pdf文档
                doc = new Document(rec);
                // 设置输出文件路径
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outFilePath, FileMode.Create));
                // 设置文档的边距为0
                doc.SetMargins(0, 0, 0, 0);
                doc.Open();
                // 随便写入些内容，不然pdf创建会失败
                PdfPTable pdfTable = new PdfPTable(1);
                pdfTable.TotalWidth = width;
                pdfTable.LockedWidth = true;
                PdfPCell cellData = new PdfPCell(new iTextSharp.text.Paragraph(""));
                cellData.BackgroundColor = iTextSharp.text.Color.BLACK;
                cellData.FixedHeight = 1F;
                pdfTable.AddCell(cellData);
                doc.Add(pdfTable);
                return true;
            }
            catch (Exception e)
            {
                Trace.WriteLine($"生成指定尺寸的PDF失败--{e.Message}");
                return false;
            }
            finally
            {
                if(doc != null)
                    doc.Close();
            }
        }

        /// <summary>
        /// 生成指定尺寸的目标文件，并返回文件路径
        /// </summary>
        /// <param name="targetFile">PDF文件</param>
        /// <param name="width">宽度（单位：毫米）</param>
        /// <param name="height">高度（单位：毫米）</param>
        /// <returns></returns>
        string AlterPdfSize(string targetFile, int width, int height)
        {
            string resultFilePath = "";
            Document doc = null;
            try
            {
                PdfReader reader = new PdfReader(targetFile);
                float newWidth = width * 2.835f;
                float newHeight = height * 2.835f;
                iTextSharp.text.Rectangle newSize = new RectangleReadOnly(newWidth, newHeight);
                doc = new Document(newSize, 0, 0, 0, 0);
                string id = Guid.NewGuid().ToString();
                resultFilePath = @"d:\" + id + ".pdf";
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(resultFilePath, FileMode.Create));
                doc.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage page = writer.GetImportedPage(reader, 1); //page #1 
                float Scale = 0.67f;
                cb.AddTemplate(page, Scale, 0, 0, Scale, 0, 0);

                return resultFilePath;
            }
            catch (Exception e)
            {
                Trace.WriteLine("添加拼版时生成指定尺寸的目标PDF出错：" + e.Message);
                return "";
            }
            finally
            {
                doc.Close();
            }
        }

        ///// <summary>
        ///// 将PDF转换为图片
        ///// </summary>
        ///// <param name="pdfPath">pdf文件位置</param>
        ///// <param name="pageNumber">pdf文件张数</param>
        ///// <param name="size">pdf文件尺寸</param>
        ///// <param name="outputPath">输出图片位置与名称</param>
        //public static void RenderPage(string pdfPath, int pageNumber, System.Drawing.Size size, string outputPath, int dpi = 300)
        //{
        //    using (var document = PdfiumViewer.PdfDocument.Load(pdfPath))
        //    using (var stream = new FileStream(outputPath, FileMode.Create))
        //    using (var image = GetPageImage(pageNumber, size, document, dpi))
        //    {
        //        image.Save(stream, ImageFormat.Jpeg);
        //    }
        //}

        ///// <summary>
        ///// 重新设置图片的长宽
        ///// </summary>
        ///// <param name="imgToResize"></param>
        ///// <param name="size"></param>
        ///// <returns></returns>
        //private System.Drawing.Image ResizeImage(System.Drawing.Image imgToResize, System.Drawing.Size size)
        //{
        //    //获取图片宽度
        //    int sourceWidth = imgToResize.Width;
        //    //获取图片高度
        //    int sourceHeight = imgToResize.Height;

        //    float nPercent = 0;
        //    float nPercentW = 0;
        //    float nPercentH = 0;
        //    //计算宽度的缩放比例
        //    nPercentW = ((float)size.Width / (float)sourceWidth);
        //    //计算高度的缩放比例
        //    nPercentH = ((float)size.Height / (float)sourceHeight);


        //    //期望的宽度
        //    int destWidth = (int)(sourceWidth * nPercentW);
        //    //期望的高度
        //    int destHeight = (int)(sourceHeight * nPercentH);

        //    Bitmap b = new Bitmap(destWidth, destHeight);
        //    Graphics g = Graphics.FromImage((System.Drawing.Image)b);
        //    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //    //绘制图像
        //    g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        //    g.Dispose();
        //    return (System.Drawing.Image)b;
        //}

        /// <summary>
        /// 创建PDF
        /// </summary>
        /// <returns></returns>
        private bool CreatePDF()
        {
            try
            {
                Document doc = new Document(PageSize.A4);//定义一个Document，并设置页面大小为A4，竖向
                MemoryStream pdfMS = new MemoryStream();
                PdfWriter.GetInstance(doc, pdfMS);//PDF内容放入到流中
                doc.Open();
                float[] colSet = { 40, 80, 70, 70, 70, 70, 70, 70, 70, 50 };//设定每列宽度
                PdfPTable pdfTable = new PdfPTable(colSet.Length); //初始化列数
                pdfTable.SetWidthPercentage(colSet, PageSize.A4);
                pdfTable.SplitLate = false;
                PdfPCell pdfPCell;//创建单元格

                #region 插入图片
                pdfPCell = new PdfPCell();

                // 生成专色
                CMYKColor curColor = new CMYKColor((float)85.9, (float)85.08, (float)78.82, (float)100);
                SpotColor spotColor = new SpotColor(new PdfSpotColor("S", 1.0F, curColor));
                // 将专色设置为单元格的背景色
                pdfPCell.BackgroundColor = spotColor;
                pdfPCell.Border = 0;
                pdfPCell.Colspan = 10;
                //pdfPCell.HorizontalAlignment = leftHAlignment;
                //iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("D:\\test.jpg");
                //pdfPCell.Image = img; //图片 
                pdfTable.AddCell(pdfPCell);
                #endregion

                doc.Add(pdfTable);
                doc.NewPage();//分页
                doc.Close();
                //保存pdf文件
                byte[] fileByte = pdfMS.GetBuffer();
                string fileName = "D:\\" + Guid.NewGuid().ToString() + ".pdf";
                FileStream fs = new FileStream(fileName, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(fileByte);
                bw.Close();
                fs.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 创建PDF
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <returns></returns>
        private bool CreatePDF(DataTable dtSource)
        {
            try
            {
                Document doc = new Document(PageSize.A4);//定义一个Document，并设置页面大小为A4，竖向
                MemoryStream pdfMS = new MemoryStream();
                PdfWriter.GetInstance(doc, pdfMS);//PDF内容放入到流中
                doc.Open();
                float[] colSet = { 40, 80, 70, 70, 70, 70, 70, 70, 70, 50 };//设定每列宽度
                PdfPTable pdfTable = new PdfPTable(colSet.Length); //初始化列数
                pdfTable.SetWidthPercentage(colSet, PageSize.A4);
                pdfTable.SplitLate = false;
                PdfPCell pdfPCell;//创建单元格

                #region
                //BaseFont baseFont = BaseFont.CreateFont("C://WINDOWS//Fonts//simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//宋体
                //BaseFont titleBaseFont = BaseFont.CreateFont("C://WINDOWS//Fonts//simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//黑体
                //Font titleFont = new Font(titleBaseFont, 7);//标题字体
                //Font contentFont = new Font(baseFont, 6);//正文字体
                //int horizontalAlignment = Element.ALIGN_CENTER;  //水平居中(单元格文字位置)
                //int verticalAlignment = Element.ALIGN_MIDDLE;   //垂直居中(单元格文字位置)
                //int leftHAlignment = Element.ALIGN_LEFT;//水平居左
                //#region 创建Table
                ////标题
                //pdfPCell = new PdfPCell(new Phrase("创建PDF测试", titleFont));
                //pdfPCell.Colspan = 10;//合并单元格,默认为1
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                ////Table列标题
                //pdfPCell = new PdfPCell(new Phrase("序号", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("报修编号", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("报修标题", titleFont));
                //pdfPCell.Colspan = 2;
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("提交时间", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("闭环时间", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("报修人", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("故障系统", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("故障等级", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //pdfPCell = new PdfPCell(new Phrase("报修进度", titleFont));
                //pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //pdfPCell.BackgroundColor = iTextSharp.text.Color.BLACK; //单元格背景颜色
                //pdfPCell.HorizontalAlignment = horizontalAlignment;
                //pdfPCell.VerticalAlignment = verticalAlignment;
                //pdfTable.AddCell(pdfPCell);

                //int sortNo = 0;//序号
                //               //表格行数据
                //foreach (DataRow dr in dtSource.Rows)
                //{
                //    //序号
                //    sortNo++;
                //    pdfPCell = new PdfPCell(new Phrase(sortNo.ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //报修编号
                //    pdfPCell = new PdfPCell(new Phrase(dr[0].ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //报修标题
                //    pdfPCell = new PdfPCell(new Phrase(dr[1].ToString(), contentFont));
                //    pdfPCell.Colspan = 2;
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //提交时间
                //    pdfPCell = new PdfPCell(new Phrase(dr[2].ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //闭环时间
                //    pdfPCell = new PdfPCell(new Phrase(dr[3].ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //报修人
                //    pdfPCell = new PdfPCell(new Phrase(dr[4].ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //故障系统
                //    pdfPCell = new PdfPCell(new Phrase(dr[5].ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //故障等级
                //    pdfPCell = new PdfPCell(new Phrase(dr[6].ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //    //报修进度
                //    pdfPCell = new PdfPCell(new Phrase(dr[7].ToString(), contentFont));
                //    pdfPCell.BorderColor = iTextSharp.text.Color.BLACK; //单元格边框颜色，默认黑色
                //    pdfPCell.HorizontalAlignment = leftHAlignment;
                //    pdfTable.AddCell(pdfPCell);
                //}
                #endregion

                #region 插入图片
                pdfPCell = new PdfPCell();
                pdfPCell.Border = 0;
                pdfPCell.Colspan = 10;
                //pdfPCell.HorizontalAlignment = leftHAlignment;
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("D:\\test.jpg");
                pdfPCell.Image = img; //图片 
                pdfTable.AddCell(pdfPCell);
                #endregion

                doc.Add(pdfTable);
                doc.NewPage();//分页
                doc.Close();
                //保存pdf文件
                byte[] fileByte = pdfMS.GetBuffer();
                string fileName = "D:\\" + Guid.NewGuid().ToString() + ".pdf";
                FileStream fs = new FileStream(fileName, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(fileByte);
                bw.Close();
                fs.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
